package org.fast.develop.logicflow.core.meta;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.fast.develop.logicflow.core.meta.builder.ElementFactory;
import org.fast.develop.logicflow.core.meta.shape.LogicFlowDefinition;
import org.fast.develop.logicflow.core.meta.base.Resource;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 莫寅
 * @createTime 2022-11-24 01:05
 * @desc：
 */
public class LogicFlowDefinitionFactory {

    private ElementFactory elementFactory;

    public LogicFlowDefinitionFactory(ElementFactory elementFactory) {
        this.elementFactory = elementFactory;
    }

    public LogicFlowDefinition create(String jsonSchema) {

        JSONObject jsonObject = JSONUtil.parseObj(jsonSchema);
        JSONArray jsonArray = jsonObject.getJSONArray("definitions");
        List<Resource> elementList = jsonArray.stream().map(s -> {
            JSONObject elementJSONObject = (JSONObject)s;
            return elementFactory.create(elementJSONObject);
        }).collect(Collectors.toList());



        LogicFlowDefinition logicFlow = new LogicFlowDefinition();
        Definitions definitions = new Definitions();
        definitions.setList(elementList);
        logicFlow.setDefinitions(definitions);


        String id = jsonObject.getStr("id");
        logicFlow.setResourceId(id);

        String version = jsonObject.getStr("version");
        logicFlow.setVersion(version);

        String name = jsonObject.getStr("name");
        logicFlow.setName(name);

        return logicFlow;
    }


}
